package cn.cdeden.knowledge.utils;

import cn.cdeden.system.api.RemoteConfigService;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.RequiredArgsConstructor;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.util.IOUtils;
import org.apache.poi.xslf.usermodel.XMLSlideShow;
import org.apache.poi.xslf.usermodel.XSLFSlide;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.xwpf.usermodel.*;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.List;

@RequiredArgsConstructor
public class ReaderUtil {

    public static String markItDown(String fileUrl, String markItDownUrl) throws IOException {
        HttpURLConnection markItDownConnection = null;

        URL url = new URL(markItDownUrl);
        markItDownConnection = (HttpURLConnection) url.openConnection();
        markItDownConnection.setRequestMethod("POST");
        markItDownConnection.setRequestProperty("Content-Type", "application/json");
        markItDownConnection.setDoOutput(true);

        // 创建一个 JSON 对象来作为请求体
        JSONObject jsonBody = new JSONObject();
        jsonBody.set("fileUrl", fileUrl);

        // 发送 JSON 数据
        try (OutputStream os = markItDownConnection.getOutputStream()) {
            byte[] input = jsonBody.toString().getBytes("utf-8");
            os.write(input, 0, input.length);
        }

        int responseCode = markItDownConnection.getResponseCode();

        if (responseCode != HttpURLConnection.HTTP_OK ) {
            throw new IOException("HTTP request failed with status code " + responseCode);
        }

        // 读取接口响应结果
        StringBuilder response = new StringBuilder();
        try (BufferedReader in = new BufferedReader(new InputStreamReader(markItDownConnection.getInputStream(), "utf-8"))) {
            String inputLine;
            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine).append("\n");
            }
        }

        return response.toString();

    }


    public static String readTextFile(String fileUrl) throws IOException {

        URL url = new URL(fileUrl);
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream(), StandardCharsets.UTF_8))) {
            StringBuilder content = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                content.append(line).append("\n");
            }
            return content.toString();
        }
    }

    public static String fileReadTextFile(MultipartFile file) throws IOException {

        // 获取文件的输入流
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(file.getInputStream(), StandardCharsets.UTF_8))) {
            StringBuilder content = new StringBuilder();
            String line;
            // 逐行读取文件内容
            while ((line = reader.readLine()) != null) {
                content.append(line).append("\n");
            }
            return content.toString();
        }
    }


    public static String readPdf(String fileUrl) throws IOException {
        URL url = new URL(fileUrl);
        try (PDDocument document = PDDocument.load(url.openStream())) {
            PDFTextStripper stripper = new PDFTextStripper();
            return stripper.getText(document);
        }
    }

    public static String fileReadPdf(MultipartFile file) throws IOException {
        try (PDDocument document = PDDocument.load(file.getInputStream())) {
            PDFTextStripper stripper = new PDFTextStripper();
            return stripper.getText(document);
        }
    }


    public static String readWord(String fileUrl) throws IOException {
        IOUtils.setByteArrayMaxOverride(50000000);
        URL url = new URL(fileUrl);
        StringBuilder content = new StringBuilder();
        try (InputStream inputStream = url.openStream();
             XWPFDocument doc = new XWPFDocument(inputStream)) {


            //提取段落中的信息
            List<XWPFParagraph> paragraphs = doc.getParagraphs();
            for (org.apache.poi.xwpf.usermodel.XWPFParagraph para : paragraphs) {
                content.append(para.getText()).append("\n");
            }

            //提取表格中的信息
            List<XWPFTable> tables = doc.getTables();
            for (XWPFTable table : tables) {
                for (XWPFTableRow row : table.getRows()) {
                    for (XWPFTableCell cell : row.getTableCells()) {
                        content.append(cell.getText()).append("\t");  // 使用制表符分隔单元格内容
                    }
                    content.append("\n");  // 每行结束后换行
                }
            }
        }

        return content.toString();

    }

    public static String fileReadWord(MultipartFile file) throws IOException {
        try (InputStream inputStream = file.getInputStream();
             XWPFDocument doc = new XWPFDocument(inputStream)) {
            StringBuilder content = new StringBuilder();
            List<XWPFParagraph> paragraphs = doc.getParagraphs();
            for (org.apache.poi.xwpf.usermodel.XWPFParagraph para : paragraphs) {
                content.append(para.getText()).append("\n");
            }
            return content.toString();
        }
    }

    public static String readExcel(String fileUrl) throws IOException {
        URL url = new URL(fileUrl);
        try (InputStream inputStream = url.openStream();
             Workbook workbook = new XSSFWorkbook(inputStream)) {
            StringBuilder content = new StringBuilder();
            Sheet sheet = workbook.getSheetAt(0); // 获取第一个sheet
            for (Row row : sheet) {
                for (Cell cell : row) {
                    content.append(cell.toString()).append("\t");
                }
                content.append("\n");
            }
            return content.toString();
        }
    }

    public static String fileReadExcel(MultipartFile file) throws IOException {
        try (InputStream inputStream = file.getInputStream();
             Workbook workbook = new XSSFWorkbook(inputStream)) {
            StringBuilder content = new StringBuilder();
            Sheet sheet = workbook.getSheetAt(0); // 获取第一个sheet
            for (Row row : sheet) {
                for (Cell cell : row) {
                    content.append(cell.toString()).append("\t");
                }
                content.append("\n");
            }
            return content.toString();
        }
    }


    public static String readPpt(String fileUrl) throws IOException {
        URL url = new URL(fileUrl);
        try (InputStream inputStream = url.openStream();
             XMLSlideShow ppt = new XMLSlideShow(inputStream)) {
            StringBuilder content = new StringBuilder();
            for (XSLFSlide slide : ppt.getSlides()) {
                content.append(slide.getTitle()).append("\n");
                slide.getShapes().forEach(shape -> {
                    if (shape instanceof org.apache.poi.xslf.usermodel.XSLFTextShape) {
                        content.append(((org.apache.poi.xslf.usermodel.XSLFTextShape) shape).getText()).append("\n");
                    }
                });
            }
            return content.toString();
        }
    }


    public static String fileReadPpt(MultipartFile file) throws IOException {
        try (InputStream inputStream = file.getInputStream();
             XMLSlideShow ppt = new XMLSlideShow(inputStream)) {
            StringBuilder content = new StringBuilder();
            for (XSLFSlide slide : ppt.getSlides()) {
                content.append(slide.getTitle()).append("\n");
                slide.getShapes().forEach(shape -> {
                    if (shape instanceof org.apache.poi.xslf.usermodel.XSLFTextShape) {
                        content.append(((org.apache.poi.xslf.usermodel.XSLFTextShape) shape).getText()).append("\n");
                    }
                });
            }
            return content.toString();
        }
    }


    public static String minerUReadPdf(String fileUrl, String MinerUUrl) throws IOException, InterruptedException {
        URL url = new URL(fileUrl);
        InputStream inputStream = url.openStream();

        //调用MinerU上传pdf文件
        MinerUUrl = MinerUUrl + "/pdf_parse";

        HttpURLConnection connection = null;

        String boundary = "----WebKitFormBoundary7MA4YWxkTrZu0gW";
        connection = (HttpURLConnection) new URL(MinerUUrl).openConnection();
        connection.setDoOutput(true);
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
        connection.setRequestProperty("Accept", "application/json");
        // 获取输出流，准备发送请求数据
        try (DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream())) {
            // 写入 PDF 文件到 FormData 中
            outputStream.writeBytes("--" + boundary + "\r\n");
            outputStream.writeBytes("Content-Disposition: form-data; name=\"pdf_file\"; filename=\"file.pdf\"\r\n");
            outputStream.writeBytes("Content-Type: application/pdf\r\n\r\n");

            // 将 PDF 文件的内容写入到输出流中
            byte[] buffer = new byte[4096];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
            outputStream.writeBytes("\r\n");

            // 结束 FormData
            outputStream.writeBytes("--" + boundary + "--\r\n");
        }
        int status = connection.getResponseCode();
        if (status != HttpURLConnection.HTTP_OK) {
            throw new IOException("调用MinerU上传PDF出错" + status);
        }

        // 获取服务器响应
        String fileKey = null;
        StringBuilder response = new StringBuilder();
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
            String line;
            while ((line = reader.readLine()) != null) {
                response.append(line);
                JSONObject body = new JSONObject(line);
                fileKey = body.getStr("md_content");


//                JSONObject data = body.getJSONObject("data");
//                fileKey = data.getStr("file_key");
            }
        }
        connection.disconnect();
        inputStream.close();
        return fileKey;






//        //调用MinerU提交PDF解析任务
//        if (fileKey.isEmpty()) {
//            throw new IOException("上传PDF文件后返回的file_key为null");
//        }
//        String MinerUSubmitUrl = "http://192.168.6.55:5559/api/v2/extract/task/submit";
//
//        HttpURLConnection submitConnection = null;
//
//        submitConnection = (HttpURLConnection) new URL(MinerUSubmitUrl).openConnection();
//        submitConnection.setDoOutput(true);
//        submitConnection.setRequestMethod("POST");
//        submitConnection.setRequestProperty("Content-Type", "application/json");
//
//        JSONObject data = new JSONObject();
//        data.set("fileKey", fileKey);
//        data.set("taskType", "pdf");
//        data.set("isOcr", true);
//
//        // 发送请求数据
//        try (OutputStream os = submitConnection.getOutputStream()) {
//            byte[] input = data.toString().getBytes("UTF-8");
//            os.write(input, 0, input.length);
//        }
//
//        int responseCode = submitConnection.getResponseCode();
//        if (responseCode != HttpURLConnection.HTTP_OK) {
//            throw new IOException("调用MinerU提交解析任务出错" + responseCode);
//        }
//
//        String id = null;
//        try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(submitConnection.getInputStream()))) {
//            String line;
//            while ((line = bufferedReader.readLine()) != null) {
//                JSONObject body = new JSONObject(line);
//                JSONObject submitData = body.getJSONObject("data");
//                id = submitData.getStr("id");
//            }
//        }
//
//        submitConnection.disconnect();
//
//
//
//        //调用MinerU查询解析任务的进度
//        String fullMdLink = null;
//        boolean isDone = false;
//        while (!isDone) {
//
//            if (id.isEmpty()) {
//                throw new IOException("提交解析任务后返回的id为null");
//            }
//
//            String MinerUExtractUrl = "http://192.168.6.55:5559/api/v2/extract/task/progress?id=" + id;
//            HttpURLConnection extractConnection = null;
//
//            extractConnection = (HttpURLConnection) new URL(MinerUExtractUrl).openConnection();
//            extractConnection.setRequestMethod("GET");
//            extractConnection.setRequestProperty("Content-Type", "application/json");
//
//            try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(extractConnection.getInputStream()))) {
//                String line;
//                while ((line = bufferedReader.readLine()) != null) {
//                    JSONObject body = new JSONObject(line);
//                    JSONObject extractData = body.getJSONObject("data");
//                    String state = extractData.getStr("state");
//                    if (state.equals("done")) {
//                        fullMdLink = extractData.getStr("fullMdLink");
//                        isDone = true;
//                    }
//                }
//            }
//
//            if (!isDone) {
//                Thread.sleep(2000);
//            }
//
//        }
//
//
//        //MinerU解析完成后读取解析后的文件
//        URL fullMdLinkUrl = new URL(fullMdLink);
//        try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(fullMdLinkUrl.openStream(), StandardCharsets.UTF_8))) {
//            String line;
//            StringBuilder mdContent = new StringBuilder();
//            while ((line = bufferedReader.readLine())!= null) {
//                mdContent.append(line).append("\n");
//            }
//            return mdContent.toString();
//        }
    }


    public static String minerUFileReadPdf(MultipartFile file, String MinerUUrl) throws IOException, InterruptedException {

        InputStream inputStream = file.getInputStream();

        //调用MinerU上传pdf文件
        MinerUUrl = MinerUUrl + "/pdf_parse";

        HttpURLConnection connection = null;

        String boundary = "----WebKitFormBoundary7MA4YWxkTrZu0gW";
        connection = (HttpURLConnection) new URL(MinerUUrl).openConnection();
        connection.setDoOutput(true);
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
        connection.setRequestProperty("Accept", "application/json");
        // 获取输出流，准备发送请求数据
        try (DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream())) {
            // 写入 PDF 文件到 FormData 中
            outputStream.writeBytes("--" + boundary + "\r\n");
            outputStream.writeBytes("Content-Disposition: form-data; name=\"pdf_file\"; filename=\"file.pdf\"\r\n");
            outputStream.writeBytes("Content-Type: application/pdf\r\n\r\n");

            // 将 PDF 文件的内容写入到输出流中
            byte[] buffer = new byte[4096];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
            outputStream.writeBytes("\r\n");

            // 结束 FormData
            outputStream.writeBytes("--" + boundary + "--\r\n");
        }
        int status = connection.getResponseCode();
        if (status != HttpURLConnection.HTTP_OK) {
            throw new IOException("调用MinerU上传PDF出错" + status);
        }

        // 获取服务器响应
        String fileKey = null;
        StringBuilder response = new StringBuilder();
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
            String line;
            while ((line = reader.readLine()) != null) {
                response.append(line);
                JSONObject body = new JSONObject(line);
                fileKey = body.getStr("md_content");

//                JSONObject data = body.getJSONObject("data");
//                fileKey = data.getStr("file_key");
            }
        }
        connection.disconnect();
        inputStream.close();

        return fileKey;

//        //调用MinerU提交PDF解析任务
//        if (fileKey.isEmpty()) {
//            throw new IOException("上传PDF文件后返回的file_key为null");
//        }
//        String MinerUSubmitUrl = "http://192.168.6.55:5559/api/v2/extract/task/submit";
//
//        HttpURLConnection submitConnection = null;
//
//        submitConnection = (HttpURLConnection) new URL(MinerUSubmitUrl).openConnection();
//        submitConnection.setDoOutput(true);
//        submitConnection.setRequestMethod("POST");
//        submitConnection.setRequestProperty("Content-Type", "application/json");
//
//        JSONObject data = new JSONObject();
//        data.set("fileKey", fileKey);
//        data.set("taskType", "pdf");
//        data.set("isOcr", true);
//
//        // 发送请求数据
//        try (OutputStream os = submitConnection.getOutputStream()) {
//            byte[] input = data.toString().getBytes("UTF-8");
//            os.write(input, 0, input.length);
//        }
//
//        int responseCode = submitConnection.getResponseCode();
//        if (responseCode != HttpURLConnection.HTTP_OK) {
//            throw new IOException("调用MinerU提交解析任务出错" + responseCode);
//        }
//
//        String id = null;
//        try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(submitConnection.getInputStream()))) {
//            String line;
//            while ((line = bufferedReader.readLine()) != null) {
//                JSONObject body = new JSONObject(line);
//                JSONObject submitData = body.getJSONObject("data");
//                id = submitData.getStr("id");
//            }
//        }
//
//        submitConnection.disconnect();
//
//
//
//        //调用MinerU查询解析任务的进度
//        String fullMdLink = null;
//        boolean isDone = false;
//        while (!isDone) {
//
//            if (id.isEmpty()) {
//                throw new IOException("提交解析任务后返回的id为null");
//            }
//
//            String MinerUExtractUrl = "http://192.168.6.55:5559/api/v2/extract/task/progress?id=" + id;
//            HttpURLConnection extractConnection = null;
//
//            extractConnection = (HttpURLConnection) new URL(MinerUExtractUrl).openConnection();
//            extractConnection.setRequestMethod("GET");
//            extractConnection.setRequestProperty("Content-Type", "application/json");
//
//            try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(extractConnection.getInputStream()))) {
//                String line;
//                while ((line = bufferedReader.readLine()) != null) {
//                    JSONObject body = new JSONObject(line);
//                    JSONObject extractData = body.getJSONObject("data");
//                    String state = extractData.getStr("state");
//                    if (state.equals("done")) {
//                        fullMdLink = extractData.getStr("fullMdLink");
//                        isDone = true;
//                    }
//                }
//            }
//
//            if (!isDone) {
//                Thread.sleep(2000);
//            }
//
//        }
//
//
//        //MinerU解析完成后读取解析后的文件
//        URL fullMdLinkUrl = new URL(fullMdLink);
//        try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(fullMdLinkUrl.openStream(), StandardCharsets.UTF_8))) {
//            String line;
//            StringBuilder mdContent = new StringBuilder();
//            while ((line = bufferedReader.readLine())!= null) {
//                mdContent.append(line).append("\n");
//            }
//            return mdContent.toString();
//        }
    }



}
